//
//  main.cpp
//  MySDLGame
//
//  Created by grg on 2020/8/2.
//  Copyright © 2020 grg. All rights reserved.
//

#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2_mixer/SDL_mixer.h>

#include "SDL2_ttf/SDL_ttf.h"
#include "ImageTexture.h"
#include "SDL2_image/SDL_image.h"
#include "GameWindowConfig.h"

#include "LTRBTTView.h"
#include "TextView.h"
#include "MixerComponent.h"
#include "TTFComponent.h"
#include "SDLWindowComponent.h"

#include "List.h"

using namespace std;


int main(int argc, const char *argv[]) {

//    List<SDL_Rect> *list = new List<SDL_Rect>(9);
//
//    for (int i = 0; i < list->maxSize(); i++) {
//        SDL_Rect rect = {0, 0, 10 * i, 1};
//        list->add(rect);
//    }
//
//    for (int i = 0; i < list->maxSize(); ++i) {
////         list->get(i)->w
//
//        SDL_Rect rect = list->get(i);
//        cout << rect.x << rect.y << rect.w << rect.h << endl;
//    }
//
//    delete list;
//
//    return 0;

    //主 组件
    gContext = new SDLWindowComponent();

    //字体组件
    TTFComponent *ttfComponent = new TTFComponent();

    //声音组件
    MixerComponent *mixer = new MixerComponent();

    //
    Mix_Chunk *chunk = Mix_LoadWAV(musicPath("scratch.wav"));

    LTRBTTView *view = new LTRBTTView();

    for (int i = 0; i < 1; ++i) {
        LTRBTTView *view2 = new LTRBTTView();
        view2->updateTargetXY(
                static_cast<int>(random() % 500 + i * 20),
                static_cast<int>(random() % 300 + i * 20));
        view->insertToChain(view2);

    }

    //显示文字
    SDL_Color color = {255, 255, 255, 255};
    TextView *textView = new TextView(ttfComponent->getHyshangweishoushuw(), "test world", color);

    view->insertToChain(textView);

    SDL_Event event;
    bool quit = false;
    Uint32 frameTime;
    while (!quit) {

        frameTime = SDL_GetTicks();

        //        SDL_FillRect(windowSurf, nullptr, 0);
        SDL_RenderClear(gContext->getRender());
        //        SDL_BlitSurface(img,&srcRect,windowSurf,&targetRect);
//        SDL_RenderCopy(render, imgTexture, nullptr, &targetRect);
        view->onDraw();

        //更新 ui
        SDL_RenderPresent(gContext->getRender());

        while (SDL_PollEvent(&event) != 0) {

            view->onEvent(&event);

            switch (event.type) {
                case SDL_QUIT:
                    quit = true;
                    break;
                case SDL_KEYDOWN:
                    //播放
                    Mix_PlayChannel(-1, chunk, 0);
                    break;
                default:
                    break;
            }
        }

        view->onPreUpdate();
        //60 ms
//        SDL_Delay(1000 / 60);

        if (SDL_GetTicks() - frameTime < MIN_FRAME_TIME) {
            SDL_Delay(MIN_FRAME_TIME - (SDL_GetTicks() - frameTime));
        }

    }

    view->kill();

    Mix_FreeChunk(chunk);
    delete mixer;
    delete ttfComponent;
    delete gContext;

    cout << "游戏结束。。。" << endl;
    return 0;
}
